<template>
  <div class="app-container">
    <div class="phone" id="test" ref="canvasImg">
      <img
        src="@/assets/header.png?imageView2/1/w/80/h/80"
        class="user-avatar"
      />
      <img :src="baseUrl" class="user-avatar" />
      <view class="content"> 文字信息 </view>
    </div>
    <el-button size="mini" type="primary" @click="submit">保存</el-button>
  </div>
</template>

<script>
import html2canvas from 'html2canvas'
export default {
  name: 'MerchantsRecharge',
  data() {
    return {
      baseUrl: '',
    }
  },
  mounted() {
    this.getBase64(
      'https://img0.baidu.com/it/u=4146947590,1577640986&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=1731'
    ).then((base64) => {
      this.baseUrl = base64
    })
  },
  methods: {
    getBase64(img_url) {
      function toBase64(image) {
        const canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        const ctx = canvas.getContext('2d')
        ctx.drawImage(image, 0, 0, image.width, image.height)
        const base64 = canvas.toDataURL('image/png')
        return base64
      }
      return new Promise((resolve, reject) => {
        const image = new Image()
        image.setAttribute('crossOrigin', 'anonymous') // 解决跨域
        image.crossOrigin = '*'
        image.src = img_url + '?v=' + Math.random() // 解决图片URL缓存问题
        image.onload = () => {
          resolve(toBase64(image))
        }
      })
    },
    async submit() {
      try {
        const element = document.getElementById('test')
        await html2canvas(element).then((canvas) => {
          const link = document.createElement('a')
          link.href = canvas.toDataURL('image/png')
          link.download = 'image.png'
          link.click()
        })
      } catch (e) {
        throw new Error(e)
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.app-container {
  .phone {
    width: 375px;
    background-color: #f00;
  }
  .user-avatar {
    width: 200px;
  }
}
</style>
